package com.example.model.log.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.annotations.Autowired;
import com.example.annotations.Service;
import com.example.auth.model.UserModel;
import com.example.auth.service.UserModelService;
import com.example.model.log.LogModel;
import com.example.model.log.service.LogHandler;
import com.example.model.log.service.LogModelService;
import com.example.utils.ObjectMaps;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;

import java.util.Date;

/**
 * @Classname LogHandlerImpl
 * @Description TODO
 * @Date 2022/8/14 12:30
 * @Created by XiongXiong
 * @Author: X.I.O
 */
@Service
public class LogHandlerImpl implements LogHandler {

    @Autowired
    LogModelService logService;

    @Autowired
    UserModelService userModelService;

    @Override
    public Object LogHandler(HttpServerRequest request, HttpServerResponse response, Object req, Object result) {
        UserModel userModel=userModelService.getUserModel();
        String ip=request.host();
        String url=request.uri();
        String urlName=ObjectMaps.getUrlName(request.uri());
        LogModel logModel=new LogModel();
        logModel.setAddress(url);
        logModel.setAddressname(urlName);
        logModel.setIpaddress(ip);
        if(req!=null){
            String reqString=JSONObject.toJSONString(req);
            if(reqString.length()>100){
                reqString=reqString.substring(0,99);
            }
            logModel.setArgs(reqString);
        }
        if(userModel!=null){
            logModel.setUserid(userModel.getId());
            logModel.setUsername(userModel.getUsername());
        }
        logModel.setCreatedate(new Date());
        logService.saveLogModel(logModel);
        return null;
    }
}
